//
//  InstallerPointsViewController.swift
//  ezyform
//
//  Created by MoennigQ on 26/12/19.
//  Copyright © 2019 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import SwiftyJSON
import HandyJSON
import MJRefresh
class RewardsViewController: ModelBaseViewController {
    var refreshMeViewClosure: (()->Void)?
    let customView = InstallerPointsView()
    var pointList = [PointModel]()
    
    //total pages for list
    var currentPage: String = ""
    var nextPage: String = ""
    var footer: MJRefreshBackNormalFooter!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view = customView
        self.customView.setTitle(R.string.localizable.rewards())
        
        self.customView.closeBtn.addTarget(self, action: #selector(dismissVC), for: UIControl.Event.touchUpInside)
        self.customView.tableView.dataSource = self
        self.customView.tableView.delegate = self
        //header
        self.customView.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerLoad(_:)))
        //footer
        self.footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerLoad(_:)))
        self.customView.tableView.mj_footer = self.footer
        
        self.customView.tipBtn.addTarget(self, action: #selector(toPointDescription), for: UIControl.Event.touchUpInside)
        //loading data
        self.loadData()
        
    }
    @objc
    func loadData(){
        self.currentPage = "1"
        if Connectivity.isConnectedToInternet {
            self.loadCurrentTotalPoints()
            self.loadPointList()
        }else{
            Tool().showFailureInfo()
        }
    }
    func loadCurrentTotalPoints(){
        let vc = PointService()
        vc.setBlockAfterNetwork({ (result , _) in
            ModelViewUtil.shared.hideLoadingView()
            if let dic = result as? NSDictionary{
                if let data = dic.object(forKey: "current_point") as? Int {
                    let currentPoints = NumberFormatter.localizedString(from: NSNumber(value: data), number: .decimal)
                    self.customView.totalPointsLabel.text = currentPoints
                }
            }
            
        }) { (code,err) in
            ModelViewUtil.shared.hideLoadingView()
            
            Tool().showErrorInfo(code,err)
        }
        ModelViewUtil.shared.showLoadingView( NSLocalizedString("Loading", comment: ""))
        
        vc.getCurrentTotalPoints()
    }
    func loadPointList(header: MJRefreshNormalHeader? = nil, footer: MJRefreshBackNormalFooter? = nil){
        let vm = PointService()
        vm.setBlockAfterNetwork({ [weak self](obj, otherInfo) -> Void in
            guard let strongSelf = self else { return  }
            //加载完再endrefreshing,解决上拉加载时tableview抖动死循环请求网络无限次加载的问题
            if let tempHeader = header {
                tempHeader.endRefreshing()
            }
            if let tempFooter = footer {
                tempFooter.endRefreshing()
            }
            //header data
            if let data = otherInfo?.object(forKey: "X-Next-Page") as? String {
                strongSelf.nextPage = data
            }
            
            if let _ = strongSelf.footer, strongSelf.nextPage != "" {
                strongSelf.footer.resetNoMoreData()
            }else{
                strongSelf.footer.endRefreshingWithNoMoreData()
            }
            
            if let result = obj {
                let json = JSON(result)
                if strongSelf.currentPage == "1" {
                    
                    strongSelf.pointList = (JSONDeserializer<PointModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<PointModel>)!
                    
                }else{
                    let temp = (JSONDeserializer<PointModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<PointModel>)!
                    strongSelf.pointList = strongSelf.pointList + temp
                }
                strongSelf.customView.tableView.reloadData()
                
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.customView.tableView.showResultView(nodataFlag: strongSelf.pointList.count == 0 ? true: false)
            
        }) { (code,err) in
            //加载完再endrefreshing,解决上拉加载时tableview抖动死循环请求网络无限次加载的问题
            if let tempHeader = header {
                tempHeader.endRefreshing()
            }
            if let tempFooter = footer {
                tempFooter.endRefreshing()
            }
            Tool().showErrorInfo(code,err)
        }
        
        vm.getPointsList(self.currentPage)
    }
    @objc func toPointDescription(){
        
        let vc = PointDescriptionViewController()
        self.navigationController!.pushViewController(vc, animated: false)
    }
    @objc func headerLoad(_ header: MJRefreshNormalHeader){
        if Connectivity.isConnectedToInternet {
            self.currentPage = "1"
            self.loadPointList(header: header)
            self.loadCurrentTotalPoints()
        }else{
            header.endRefreshing()
            Tool().showFailureInfo()
        }
    }
    
    @objc func footerLoad(_ footer: MJRefreshBackNormalFooter){
        if Connectivity.isConnectedToInternet {
            self.currentPage = self.nextPage
            self.loadPointList(footer: footer)
        }else{
            footer.endRefreshing()
            Tool().showFailureInfo()
        }
    }
}
extension RewardsViewController: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.pointList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : PointHistoryTableViewCell! = tableView.dequeueReusableCell(withIdentifier: PointHistoryTableViewCell.reuseCellIdentifier) as? PointHistoryTableViewCell
        if (cell == nil){
            cell = PointHistoryTableViewCell(style: .default, reuseIdentifier: PointHistoryTableViewCell.reuseCellIdentifier)
        }
        
        cell!.setData(indexPath.row,list: self.pointList)
        return cell
    }
    
}
